package com.wcar.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wcar.common.entity.GoodsImage;
import com.wcar.common.entity.Product;
import com.wcar.common.vo.Result;
import com.wcar.product.controller.ProductImageController;
import com.wcar.product.dao.ProductDao;
import com.wcar.product.dao.ProductImageDao;
import com.wcar.product.service.ProductImageService;
import com.wcar.product.vo.ProductImageVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class ProductImageServiceImpl implements ProductImageService {
    @Autowired
    private ProductImageDao productImageDao;
    @Autowired
    private ProductDao productDao;
    @Override
    public Result<Page<GoodsImage>> select(ProductImageVo productImageVo) {
        Page<GoodsImage> page = new Page<>(productImageVo.getCurrentPage(),productImageVo.getPageSize());
        QueryWrapper<GoodsImage> wrapper = new QueryWrapper<>();
        List<Product> products = null;
        if (productImageVo.getProductName() != null){
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("product_name",productImageVo.getProductName());
            products = productDao.selectList(queryWrapper);
        }
        ArrayList<Integer> list = new ArrayList<>();
        if (products!=null){
            for(Product p: products){
                list.add(p.getProductId());
            }
        }
        if(list.size()==0){
            return new Result<>(201,"查询商品图片成功",new Page<>());
        }
        wrapper.in("product_id",list);
        Page<GoodsImage> goodsImagePage = productImageDao.selectPage(page, wrapper);
        if(products!=null){
            for (Product p: products) {
                for (GoodsImage g: goodsImagePage.getRecords()){
                    if (p.getProductId().equals(g.getProductId())){
                        g.setProductName(p.getProductName());
                    }
                }
            }
        }
        return new Result<>(200,"查询商品图片成功",goodsImagePage);
    }

    @Override
    public Result<GoodsImage> insertProductImage(GoodsImage goodsImage) {
        int insert = productImageDao.insert(goodsImage);
        return new Result<>(200,"添加商品图片成功",goodsImage);
    }

    @Override
    public Result<GoodsImage> updateProductImage(GoodsImage goodsImage) {
        int i = productImageDao.updateById(goodsImage);
        return new Result<>(200,"修改商品图片成功",goodsImage);
    }

    @Override
    public Result<GoodsImage> deleteProductImageById(Integer id) {
        int i = productImageDao.deleteById(id);
        return new Result<>(200,"删除商品图片成功",null);
    }
}
